package controllers;

import helpers.GeneralHelper;
import helpers.StringHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.cache.Cache;
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;

import quercus.CompileScriptEngine;

import systems.Recently;
import systems.RecentlyTag;

import models.ArticleModel;
import models.CategoryModel;
import models.UserModel;

import entities.ApplicationConfig;
import entities.ApplicationTemplate;
import entities.Article;
import entities.Category;
import entities.SeoData;
import entities.User;

public class ArticleInfoServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		ApplicationTemplate appTemplate = (ApplicationTemplate) request.getAttribute("sysTemplate");
		
		if (appTemplate == null) {
			response.getWriter().println("Please enter template");
			return ;
		}
		
		Cache memCache = GeneralHelper.getCache();
		
		User user = (User) request.getAttribute("user_logged_in");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String alias = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = articleModel.getArticleByAlias(appConfig.getApplicationId(), alias, language);
		
		if (article == null) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		if (article.getStatus() == 0) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		Category category = categoryModel.getCategory(appConfig.getApplicationId(), article.getCategory());
		
		//Get related by category
		List<Article> cArticles = articleModel.getRelatedByCategory(appConfig.getApplicationId(), article.getCategory(), language);
		
		//Get author
		UserModel userModel = UserModel.getInstance();
		User author = null;
		if (!article.getCreator().isEmpty()) {
			author = userModel.getUser(appConfig.getApplicationId(), article.getCreator());
		}
		
		//Get related by author
		List<Article> uArticles = new ArrayList<Article>();
		if (author != null) {
			uArticles = articleModel.getRelatedByAuthor(appConfig.getApplicationId(), article.getCreator(), language);
		}
		
		
		Recently.update(appConfig.getApplicationId(), article);
		
		
		//Get image
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		ImagesService imagesService = ImagesServiceFactory.getImagesService();
		
		String image = "";
		
		if (author != null && author.getAvatar() != null && !author.getAvatar().isEmpty())  {
			 BlobKey blobKey = new BlobKey(author.getAvatar());
			 image = imagesService.getServingUrl(blobKey);
		}
		
		//Get list category
		List<Category> lstCategories = categoryModel.getAll(appConfig.getApplicationId());
		
		//Get tags
		List<String> tags = RecentlyTag.getTags(appConfig.getApplicationId());
		
		//Get recently article view
		List<Article> lastestArticles = Recently.getArticles(appConfig.getApplicationId(), "", "lastest_article");
		
		//Get Seo Data 
		SeoData seoData = new SeoData();
		
		/******************************Set page template ******************************/
		String layout_for_content = "";
		String layout_for_header = "";
		String layout_for_footer = "";
		
		String cacheLayoutName = appConfig.getApplicationId() + "_layout";
		String cacheHeaderName = appConfig.getApplicationId() + "_header";
		String cacheFooterName = appConfig.getApplicationId() + "_footer";
		String cacheContentName = appConfig.getApplicationId() + "_" + alias;
		
		layout_for_content = (String) memCache.get(cacheContentName);
		if (layout_for_content == null) {
			//String contentPage = StringHelper.getContentPhp("/templates/classic/article_info.php", getServletContext());
			String contentPage = appTemplate.getArticleInfo();
			String library = appTemplate.getLibrary();
			CompiledScript compiledContent = CompileScriptEngine.getCompileScript(appConfig.getApplicationId(), "layout_for_content", contentPage);
			
			//Set value
			if (compiledContent != null) {
				Bindings bind = compiledContent.getEngine().getBindings(ScriptContext.ENGINE_SCOPE);
				bind.put("article", article);
				bind.put("cArticles", cArticles);
				bind.put("uArticles", uArticles);
				bind.put("author", author);
				bind.put("category", category);
				bind.put("image", image);
				bind.put("lstCategories", lstCategories);
				bind.put("tags", tags);
				bind.put("lastestArticles", lastestArticles);
				bind.put("user", user);
				bind.put("baseUrl", appTemplate.getBaseUrl());
				bind.put("library", library);
				bind.put("seoData", seoData);
			}
			
			try {
				layout_for_content = (String) compiledContent.eval();
			} catch (Exception e) {
				// TODO: handle exception
			}

			//memCache.put(cacheContentName, layout_for_content);
		} 
		
		layout_for_header = (String) memCache.get(cacheHeaderName);
		if (layout_for_header == null) {
			//String headerPage = StringHelper.getContentPhp("/templates/classic/header.php", getServletContext());
			String headerPage = appTemplate.getHeader();
			CompiledScript compiledHeader = CompileScriptEngine.getCompileScript(appConfig.getApplicationId(), "layout_for_header", headerPage);
			try {
				layout_for_header = (String) compiledHeader.eval();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			memCache.put(cacheHeaderName, layout_for_header);
		}
		
		
		layout_for_footer = (String) memCache.get(cacheFooterName);
		if (layout_for_footer == null) {
			//String footerPage = StringHelper.getContentPhp("/templates/classic/footer.php", getServletContext());
			String footerPage = appTemplate.getFooter();
			CompiledScript compiledFooter = CompileScriptEngine.getCompileScript(appConfig.getApplicationId(), "layout_for_footer", footerPage);
			try {
				layout_for_footer = (String) compiledFooter.eval();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			memCache.put(cacheFooterName, layout_for_footer);
		}
		
		String layoutPage = (String) memCache.get(cacheLayoutName);
		if (layoutPage == null) {
			//layoutPage = StringHelper.getContentPhp("/templates/classic/layouts.php", getServletContext());
			layoutPage = appTemplate.getLayout();
			memCache.put(cacheLayoutName, layoutPage);
		}
		
		layoutPage = layoutPage.replace("$layout_for_header", layout_for_header);
		layoutPage = layoutPage.replace("$layout_for_content", layout_for_content);
		layoutPage = layoutPage.replace("$layout_for_footer", layout_for_footer);
		layoutPage = layoutPage.replace("__META_TITLE__", seoData.getTitle());
		layoutPage = layoutPage.replace("__META_DESCRIPTION__", seoData.getDescription());
		layoutPage = layoutPage.replace("__META_KEYWORD__", seoData.getKeywords());
		layoutPage = layoutPage.replace("__OG_SITE_NAME__", seoData.getOgSiteName() == null ? "localhost:8888" : seoData.getOgSiteName());
		layoutPage = layoutPage.replace("__OG_TITLE__", seoData.getOgTitle());
		layoutPage = layoutPage.replace("__OG_DESCRIPTION__", seoData.getOgDescription());
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		try {
			response.getWriter().print(layoutPage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
